<template>
  <div class="common-layout">
    <el-container v-loading="exportLoading">
      <el-header style="min-height: 11vh; margin-top: 1vh">
        <div class="header-content common-div-card">
          <el-form :model="headerSearchForm" label-width="auto" :inline="true">
            <el-form-item label="开始时间">
              <el-date-picker v-model="headerSearchForm.startTime" type="datetime" placeholder="开始时间" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker v-model="headerSearchForm.endTime" type="datetime" placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="出口卷号">
              <el-input v-model="headerSearchForm.extId" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button type="primary" @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleExport">导出</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main>
        <div class="table-container common-div-card">
          <el-table
            :data="tableData"
            :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            v-loading="loading"
            ref="tableRef"
          >
            <el-table-column prop="serialNumber" label="序号" fixed="left" type="index" width="60px" />
            <el-table-column prop="entid" label="入口卷号" />
            <el-table-column prop="extid" label="出口卷号" />
            <el-table-column prop="steelgrade" label="钢种类型" />
            <el-table-column prop="outMatThk" label="出口最大厚度" />
            <el-table-column prop="inMatThk" label="入口最大厚度" />
            <el-table-column prop="cglRcsStripTempActAvg" label="快冷段带温实际-平均值" />
            <el-table-column prop="cglRcsStripTempSetAvg" label="快冷段带温设定-平均值" />
            <el-table-column prop="cglGiZnpotTempAvg" label="GI锌锅温度-平均值" />
            <el-table-column prop="cglGaZnpotTempAvg" label="GA锌锅温度-平均值" />
            <el-table-column prop="toc" label="创建时间" />
          </el-table>
        </div>
        <div class="pagination common-div-card">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted } from 'vue';
  import { ElMessage, ElTable } from 'element-plus';
  import { tbZincPotOutApi } from '/@/api/znpot/index';

  interface SearchForm {
    extId: string;
    startTime: string;
    endTime: string;
  }
  // 表单数据
  const headerSearchForm = reactive<SearchForm>({
    extId: '',
    startTime: '',
    endTime: '',
  });

  // 表格数据
  const tableData = ref<any>([]);
  const tableRef = ref<InstanceType<typeof ElTable>>();
  const loading = ref(false);
  const exportLoading = ref(false);

  // 分页数据
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取表格数据
  const fetchTableData = async () => {
    loading.value = true;
    try {
      const param = {
        page: {
          pageIndex: pagination.currentPage,
          pageSize: pagination.pageSize,
        },
        dto: {
          extid: headerSearchForm.extId,
          startToc: headerSearchForm.startTime,
          endToc: headerSearchForm.endTime,
        },
      };
      const res = await tbZincPotOutApi.getMoltenZincHistory(param);
      tableData.value = res.data.data;
      pagination.total = res.data.count;
      loading.value = false;
    } catch (error) {
      loading.value = false;
      ElMessage.error('获取数据失败');
    }
  };

  // 设置默认两周时间范围：当日 23:59:59 与 两周前 00:00:00
  const pad = (num: number) => (num < 10 ? `0${num}` : `${num}`);
  const formatDateTime = (d: Date) => {
    const y = d.getFullYear();
    const m = pad(d.getMonth() + 1);
    const day = pad(d.getDate());
    const hh = pad(d.getHours());
    const mm = pad(d.getMinutes());
    const ss = pad(d.getSeconds());
    return `${y}-${m}-${day} ${hh}:${mm}:${ss}`;
  };

  const setDefaultTwoWeeks = () => {
    const now = new Date();
    const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
    const startDate = new Date(end);
    startDate.setDate(end.getDate() - 13); // 包含当天，共 14 天
    startDate.setHours(0, 0, 0, 0);

    headerSearchForm.startTime = formatDateTime(startDate);
    headerSearchForm.endTime = formatDateTime(end);
  };

  // 查询方法
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchTableData();
  };

  // 重置方法
  const handleReset = () => {
    (Object.keys(headerSearchForm) as Array<keyof SearchForm>).forEach((key) => {
      headerSearchForm[key] = '';
    });
    handleSearch();
  };

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchTableData();
  };

  // 页码变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData();
  };

  // 导出
  const handleExport = async () => {
    try {
      exportLoading.value = true;
      const param = {
        startToc: headerSearchForm.startTime,
        endToc: headerSearchForm.endTime,
      };
      await tbZincPotOutApi.exportMoltenZincHistory(param);
      ElMessage.success('导出成功');
    } catch (error) {
      ElMessage.error('导出失败');
    } finally {
      exportLoading.value = false;
    }
  };

  // 生命周期钩子
  onMounted(() => {
    setDefaultTwoWeeks();
    fetchTableData();
  });

  onUnmounted(() => {});
</script>
<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  @box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
  @border: 1px solid #dcdfe6;

  .common-div-card {
    box-shadow: @box-shadow;
    transition: 0.3s;
    border-radius: @border-radius;
    border: @border;

    // 悬停状态
    &:hover {
      box-shadow: @box-shadow-hover;
    }
  }

  .common-layout {
    width: 99vw;
    min-height: 100vh;
    background-color: #fff;
  }

  .header-content {
    display: flex;
    justify-content: flex-start;
    padding: 2rem;
    min-height: 10vh;
  }

  .table-container {
    padding: 0.5rem;
    height: 70vh;

    :deep(.el-table) {
      height: 100%;
      max-width: 100%;
    }
  }

  .pagination {
    margin-top: 1h;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
  }
</style>
